package java_thinking.unit_18_IO._18_11;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.*;

import static java_thinking.net.mindview.util.Print.print;

/**
 * @Desc:   Checksum：用来计算和校验文件的检验和 的方法，一共有两种Checksum类型：Adler32(更快)，CRC32(慢些，但更准确)
 *          ZipEntry:允许你获取和设置Zip文件内该特定项上所有可以利用的数据：名字、压缩的和未压缩的文件大小、日期、
 *                  CRC校验和、额外字段数据、注释、压缩方法以及它是否是一个目录入口等等，
 * @author: cww
 * @DateTime: 2019-05-18 15:26
 */

public class ZipCompress {
    private static String file1 = "src/maindemo/java/java_thinking/unit_18_IO/_18_11/ZipCompress.gz";
    private static String file = "src/maindemo/java/java_thinking/unit_18_IO/_18_8/Redirecting.txt";
    private static String file2 = "src/maindemo/java/java_thinking/unit_18_IO/_18_6/BasicFileOutput.txt";

    public static void main(String[] args) throws IOException {
        FileOutputStream f = new FileOutputStream(file1);
        CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
        ZipOutputStream zos = new ZipOutputStream(csum);
        BufferedOutputStream out = new BufferedOutputStream(zos);
        String[] arg1 = new String[]{file,file2};
        zos.setComment("A test of java zipping");
        for (String s : arg1) {
            print("Writing file " + s);
            BufferedReader in = new BufferedReader(new FileReader(s));
            //对于每一个要加入压缩档案的文件，都必须调用putNextEntry(),并将其传递给一个ZipEntry对象
            zos.putNextEntry(new ZipEntry(s));
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
            }
            in.close();
            out.flush();
        }
        out.close();
        print("Checksum: " + csum.getChecksum().getValue());
        print("Reading file");
        FileInputStream fi = new FileInputStream(file1);
        CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
        ZipInputStream in2 = new ZipInputStream(csumi);
        BufferedInputStream bis = new BufferedInputStream(in2);
        ZipEntry ze;
        while ((ze = in2.getNextEntry()) != null) {
            print("Reading file " + ze);
            int x;
            while ((x = bis.read()) != -1) {
                System.out.print(x);
            }
        }
        if (arg1.length == 2) {
            System.out.println("Checksum: " + csumi.getChecksum().getValue());
            bis.close();
            //解压缩的便捷方法
            ZipFile zf = new ZipFile(file1);
            Enumeration e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze2 = (ZipEntry)e.nextElement();
                System.out.println("File: " + ze2);
            }
        }
    }
}
